#include "threadpool.hpp"
#include <iostream>
#include <vector>
#include <queue>
#include <memory>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <future>
#include <functional>
#include <stdexcept>
#include <sstream>

// 1.无参数，无返回值
void test1() {
    //! 使用 std::ostringstream 预构建输出内容，防止 std::cout 被多线程打断
    std::ostringstream oss;
    oss << "test1: tid = " << std::this_thread::get_id() << std::endl;
    std::cout << oss.str();
    std::this_thread::sleep_for(std::chrono::seconds(1)); // 模拟任务耗时
}

// 2.有返回值，无参数
int test2() {
    int retval = 1;
    std::ostringstream oss;
    oss << "test2: tid = " << std::this_thread::get_id() << ", retval = " << retval << std::endl;
    std::cout << oss.str();
    std::this_thread::sleep_for(std::chrono::seconds(2));
    return retval;
}

// 3.有参数，有返回值
int test3(int a, int b) {
    std::ostringstream oss;
    oss << "test2: tid = " << std::this_thread::get_id() << ", args = " << a << ", " << b << std::endl;
    std::cout << oss.str();
    std::this_thread::sleep_for(std::chrono::seconds(3));
    return a + b;
}

int main() {
    ThreadPool pool(4);
    std::vector<std::future<int>> results;

    for (int i = 0; i < 10; ++i) {
        if(i % 3 == 0) pool.enqueue(test1);
        else if(i % 3 == 1) results.emplace_back(pool.enqueue(test2));
        else results.emplace_back(pool.enqueue(test3, i, i * 2));
    }

    std::vector<bool> completed(results.size(), false);
    int remaining = results.size();

    // 或者创建新的线程监控也可以
    while (remaining > 0) {
        for (size_t i = 0; i < results.size(); ++i) {
            if (completed[i]) continue;

            // 检查任务是否已完成（非阻塞）
            std::future_status status = results[i].wait_for(std::chrono::milliseconds(10));
            if (status == std::future_status::ready) {
                auto res = results[i].get();    //! 先把future的值取出来，防止与锁冲突导致死锁
                std::ostringstream oss;
                oss << "task" << i << " result: " << res << std::endl;
                std::cout << oss.str();
                completed[i] = true;
                remaining--;
            }
        }
        // 短暂休眠，避免空轮询占用CPU
        std::this_thread::sleep_for(std::chrono::milliseconds(50));
    }

    return 0;
}
